package com.blog.controller;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.blog.entity.Blogger;
import com.blog.service.background.Impl.BloggerService;

@Controller
@RequestMapping("")
public class LoginController {
	@Autowired
	private BloggerService bloggerService;

	@RequestMapping("/loginBlogger")
	public String login(Model model,Blogger blogger) {
		//获取当前用户的shiro信息
		Subject currentUser = SecurityUtils.getSubject();  
		if (currentUser.isAuthenticated()) {
			return "redirect:/background/backgroundIndex";
		}
		//token安全令牌
		UsernamePasswordToken token = new UsernamePasswordToken(blogger.getUserName(), blogger.getPassword()); 
		 try {  
			 	//调用登录,会自动进入realm
	            currentUser.login(token);
	            Session session=currentUser.getSession();
	            session.setAttribute("subject", currentUser);
	            //登陆成功
	            return "redirect:/background/backgroundIndex";
	            
	            //登陆失败.抛出异常
	        } catch (AuthenticationException e) {  
	            model.addAttribute("error", "验证失败");  
	            return "/background/login.jsp"; 
	       }  
	}
	
	
	@RequestMapping("/getBloggerInfo")
	public String getBloggerInfo(Model model) {
		Blogger blogger = bloggerService.getBlogger();
		model.addAttribute("blogger",blogger);
		model.addAttribute("mainPage", "./blogger/bloggerInfo.jsp");
		model.addAttribute("pageTitle","关于博主_Java开源博客系统");
		return "/forground/index.jsp";
	}
	
	
	
	
	
}
